package com.ztjava.core.base;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.core.Controller;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.xiaoleilu.hutool.date.DateUtil;
import com.ztjava.core.Constant;
import com.ztjava.core.annotation.ControllerClass;
import com.ztjava.core.client.Client;
import com.ztjava.core.utiliy.RequestUtil;

public class BaseController extends Controller{	

	//客户端
	protected Client client;
	public BaseController(){
		super();
		try {
			client = this.getClass().getAnnotation(ControllerClass.class).client().newInstance();
		} catch (Exception e) {
		}
	}

	protected Map<String,String[]> getParaMapCustom(){
		return new HashMap<String, String[]>(super.getParaMap());
	}
	protected Map<String,String[]> getParaMapCustom(String[]... params){
		Map<String,String[]> map = new HashMap<String, String[]>(super.getParaMap());
		for(String[] param:params){
			map.put(param[0], new String[]{param[1]});
		}
		return map;
	}
	protected Map<String,String[]> setParaMap(Map<String,String[]> map,String key,String value){
		map.put(key, new String[]{value});
		return map;
	}
	protected Map<String,String[]> setParaMap(Map<String,String[]> map,String key,Integer value){
		map.put(key, new String[]{value+""});
		return map;
	}
	
	//自动保存Model
	public void saveModel(Model<?> model,Integer user_id){
		if(model.get("id")!=null&&model.getInt("id")>0){
			model.set("update_time", DateUtil.now());
			model.set("update_user", user_id);
			model.update();
		}else {
			model.set("create_time", DateUtil.now());
			model.set("create_user", user_id);
			model.save();
		}
	}

	protected void renderRedirect(String redirect){
		try {
			getResponse().sendRedirect(redirect);
		} catch (IOException e) {
			e.printStackTrace();
		}
		renderNull();
	}
	protected void renderSuccess(){
		renderSuccess("操作成功！");
	}
	protected void renderSuccess(String[] ext){

		setAttr(Constant.RESULT, Constant.SUCCESS);
		setAttr(Constant.MESSAGE, "操作成功！");
		setAttr(ext[0], ext[1]);
		renderJson(new String[]{Constant.RESULT,Constant.MESSAGE,ext[0]});
	}
	protected void renderSuccess(String message){
		setAttr(Constant.RESULT, Constant.SUCCESS);
		setAttr(Constant.MESSAGE, message);
		renderJson(new String[]{Constant.RESULT,Constant.MESSAGE});
	}
	protected void renderError(String message){
		setAttr(Constant.RESULT, Constant.ERROR);
		setAttr(Constant.MESSAGE, message);
		renderJson(new String[]{Constant.RESULT,Constant.MESSAGE});
	}
	protected void renderError(String message,String code){
		setAttr(Constant.RESULT, Constant.ERROR);
		setAttr(Constant.MESSAGE, message);
		setAttr("code", code);
		renderJson(new String[]{Constant.RESULT,Constant.MESSAGE,"code"});
	}
	
	protected void renderRet(Ret ret) {
		String[] json = new String[ret.size()];
		int i = 0;
		for(Object key:ret.keySet()){
			json[i] = key.toString();
			setAttr(key.toString(), ret.get(key));
			i = i + 1;
		}
		renderJson(json);
	}
	protected void renderListRet(List<Ret> list){
		if(list.size()>0){
			renderRet(list.get(0));
		}else {
			renderError("没有响应信息!");
		}
	}
	/***
	 * 同样的链接，支持移动端显示不同模板内容
	 * @param html
	 */
	protected void renderUAgent(String html) {
		if(RequestUtil.isMoblie(getRequest())){
			render("m/"+html);
		}else {
			render(html);
		}
	}
	/***
	 * 支持自定义模板
	 */
	protected void renderCustom() {
		render(getAttrForStr(Constant.CUSTOMTEMPLATE));
	}
	/***
	 * 数据表格输出数据转换
	 * @param pd
	 */
	protected void renderPageJson(Page<?> pd){
		if(client.getSkin()==null){
			setAttr(Constant.RESULT, Constant.SUCCESS);
			setAttr(Constant.MESSAGE, "操作成功！");
			setAttr("pd",pd);
			renderJson(new String[]{Constant.RESULT,Constant.MESSAGE,"pd"});
			return;
		}
		switch (client.getSkin()) {
			case Client.skin_hplus:
				setAttr("total", pd.getTotalRow());
				setAttr("rows", pd.getList());
				renderJson(new String[]{"total","rows"});
				break;
			case Client.skin_layui:
				JSONObject result = new JSONObject();
				result.put("code", 0);
				result.put("msg", "");
				result.put("count", pd.getTotalRow());
				result.put("data", pd.getList());
				result.put("page", pd.getPageNumber());
				result.put("limit", pd.getPageSize());
				renderJson(result);
			default:
				break;
		}
	}
	

	
	protected void renderUpload(Ret ret){
		if(getPara("ui","form").equals("xheditor")){
			if(ret.getStr(Constant.RESULT).equals(Constant.ERROR)) {
				renderJson(Ret.create("err", ret.getStr(Constant.MESSAGE)));
			}else {
				setAttr("err", "");
				JSONObject msg = new JSONObject();
				msg.put("url", ret.getStr("server")+ret.getStr("filePath"));
				setAttr("msg",msg);
				renderJson(new String[]{"err","msg"});
			}
			return;
		}else if(getPara("ui","form").equals("layui")){
			if(ret.getStr(Constant.RESULT).equals(Constant.SUCCESS)){
				JSONObject json = new JSONObject();
				json.put("code", 0);
				json.put("msg", "");
				JSONObject data = new JSONObject();
				data.put("src",  ret.getStr("server")+ret.getStr("filePath"));
				data.put("title", ret.getStr("name"));
				json.put("data", data);
				renderJson(json);
			}else {
				renderJson(Ret.create("code", 500).set("msg", ret.getStr(Constant.MESSAGE)));
			}
			return;
		}
		renderRet(ret);
	}
}
